import React, { useState, useEffect } from "react";
import Taro from "@tarojs/taro";
import { View, Image } from "@tarojs/components";
import {
  Button,
  Input,
  Row,
  Col,
  Form,
  FormItem,
  ImagePreview,
  ConfigProvider,
  Steps,
  Step,
  TextArea,
} from "@nutui/nutui-react-taro";
import Drivingup from "@/assets/Drivingup.png";
import Driving from "@/assets/Driving.png";
import CardFront from "@/assets/CardFront.png";
import CardBack from "@/assets/CardBack.png";
import { Close } from "@nutui/icons-react-taro";
import "./index.less";
import AuthUtil from "../../utils/api/auth";
import { UploadResponse } from "../../../types/global";

// 定义用户信息的类型
interface UserInfo {
  name: string;
  gender: string;
  ethnicity: string;
  birthDate: string;
  idNumber: string;
  contactAddress: string;
}

function DrivingLicense() {
  const instance = Taro.getCurrentInstance();
  const formData = instance?.router?.params?.formData;

  const type = instance?.router?.params?.type;
  const params = formData ? JSON.parse(formData || ("{}" as string)) : {};
  const initialFormData = params.formData
    ? JSON.parse(params.formData || "{}")
    : {}; // 解析传递的 formData

  const [drivingLicenseFront, setDrivingLicenseFront] = useState(null);
  const [drivingLicenseBack, setDrivingLicenseBack] = useState(null);
  const [idCardFront, setIdCardFront] = useState(null);
  const [idCardBack, setIdCardBack] = useState(null);
  const [images, setImages] = useState<string[]>([]); // 这里指定了类型为字符串数组
  const [showPreview, setShowPreview] = useState(false);

  const [drivingLicenseFrontId, setDrivingLicenseFrontId] = useState(null);
  const [drivingLicenseBackId, setDrivingLicenseBackId] = useState(null);
  const [idCardFrontId, setIdCardFrontId] = useState(null);
  const [idCardBackId, setIdCardBackId] = useState(null);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [form] = Form.useForm();

  // 在表单中设置初始值
  React.useEffect(() => {
    if (initialFormData) {
      form.setFieldsValue(initialFormData);
    }
  }, [initialFormData, form]);

  const submitFailed = (error: any) => {
    // Taro.showToast({ title: JSON.stringify(error), icon: 'error' });
  };

  const submitSucceed = (values: any) => {
    console.log(initialFormData, formData, params, "values");
    if (
      drivingLicenseFront &&
      drivingLicenseBack &&
      idCardFront &&
      idCardBack
    ) {
      // 所有图片都已上传，准备数据
      const formData = {
        ...initialFormData, // 合并传递的参数
        ...values,
        ...params,
        vehicleRegistrationCertificateFront: drivingLicenseFrontId,
        vehicleRegistrationCertificateBack: drivingLicenseBackId,
        identityFront: idCardFrontId,
        identityBack: idCardBackId,
      };

      // if (formData.name != formData.realName) {
      //   return Taro.showToast({ title: '行驶证姓名跟身份证不匹配', icon: 'none' });
      // }
      // 将表单数据转换为 JSON 字符串
      console.log(formData, "formData");
      const formDataString = JSON.stringify(formData);

      // 导航到个人信息页面，并传递参数
      Taro.navigateTo({
        url: `/pages/personInfo/index?type=${type}&formData=${formDataString}`,
      });
    } else {
      // 检查哪些图片没有上传
      let missingUploads: Array<string> = [];

      if (!drivingLicenseFront) {
        missingUploads.push("行驶证正面");
      }
      if (!drivingLicenseBack) {
        missingUploads.push("行驶证反面");
      }
      if (!idCardFront) {
        missingUploads.push("身份证正面");
      }
      if (!idCardBack) {
        missingUploads.push("身份证反面");
      }

      // 提示没有上传的图片信息
      Taro.showToast({
        title: `请上传以下图片: ${missingUploads.join(", ")}`,
        icon: "none",
      });

      return; // 终止后续操作
    }
  };

  // 格式化日期函数
  const formatDate = (date) => {
    return `${date.substring(0, 4)}/${date.substring(4, 6)}/${date.substring(
      6,
      8
    )}`;
  };

  const handleImageSelect = (setType, type: string) => {
    Taro.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success: (res) => {
        console.log(res, "sss");
        const imagePath = res.tempFiles[0].path;
        setType(imagePath); // 更新图片路径
        // 读取图片文件并转换为base64
        Taro.getFileSystemManager().readFile({
          filePath: imagePath,
          encoding: "base64",
          success: (data) => {
            const imageBase64: any = data.data;
            // convertImageToTempFile(imagePath, type);
            uploadFile(imagePath, type);
            Taro.showToast({
              title: "OCR识别加载中",
              icon: "loading",
              duration: 10000, // 持续显示
            });

            // 根据类型设置请求的URL和参数
            let url;
            let requestData = {};

            if (type.startsWith("id")) {
              // 身份证
              url = "https://car-admin.xipeisoft.com/api/ocr/idcard";
              requestData = {
                image: imageBase64,
                id_card_side: type === "idFront" ? "front" : "back", // 根据正反面设置
              };
            } else if (type.startsWith("driving")) {
              // 行驶证
              url = "https://car-admin.xipeisoft.com/api/ocr/vehicle-license";
              requestData = {
                image: imageBase64,
                side: type === "drivingFront" ? "front" : "back", // 根据正反面设置
              };
            } else {
              Taro.showToast({
                title: "不支持的类型",
                icon: "none",
              });
              return;
            }

            // 调用OCR服务
            Taro.request<OCRResponse>({
              url: url,
              method: "POST",
              data: requestData,
              header: {
                "Content-Type": "application/json",
              },
            })
              .then((response) => {
                if (response.data.idcard_number_type == -1)
                  return Taro.showToast({
                    title: `照片识别失败，请检查图片`,
                    icon: "none",
                  });
                Taro.hideToast();

                if (response.statusCode === 200 && response.data.words_result) {
                  const result = response.data.words_result;

                  // 更新用户信息
                  setUserInfo({
                    name: result["姓名"]?.words || "",
                    gender: result["性别"]?.words || "",
                    ethnicity: result["民族"]?.words || "",
                    birthDate: result["出生"]?.words || "",
                    idNumber: result["公民身份号码"]?.words || "",
                    contactAddress: result["住址"]?.words || "",
                  });

                  if (type === "idFront") {
                    // 更新表单值
                    form.setFieldsValue({
                      realName: result["姓名"]?.words || "",
                      identityNumber: result["公民身份号码"]?.words || "",
                      contactAddress: result["住址"]?.words || "",
                    });
                  } else if (type === "idBack") {
                    // 提取日期字符串
                    const issueDate = result["签发日期"].words;
                    const expiryDate = result["失效日期"].words;
                    const formattedIssueDate = formatDate(issueDate);
                    const formattedExpiryDate = formatDate(expiryDate);

                    // 组合成一个字段
                    const idCardDate = `${formattedIssueDate}-${formattedExpiryDate}`;
                    form.setFieldsValue({
                      idCardDate,
                    });
                  } else if (type === "drivingFront") {
                    form.setFieldsValue({
                      plateNumber: result["号牌号码"]?.words || "",
                      vehicleIdentificationNumber:
                        result["车辆识别代号"]?.words || "",
                      engineNumber: result["发动机号码"]?.words || "",
                      brandModel: result["品牌型号"]?.words || "",
                      vehicleType: result["车辆类型"]?.words || "",
                      name: result["所有人"]?.words || "",
                    });
                  } else if (type === "drivingBack") {
                    console.log(
                      parseInt(result["核定载人数"]?.words),
                      "parseInt(result['核定载人数']?.words)"
                    );
                    form.setFieldsValue({
                      ratedCapacity:
                        parseInt(result["核定载人数"]?.words) || "",
                    });
                  }
                } else {
                  Taro.showToast({
                    title: `照片识别失败，状态码：${response.statusCode}`,
                    icon: "none",
                  });
                }
              })
              .catch((error) => {
                console.error("照片识别错误:", error);
                Taro.showToast({
                  title: "网络请求失败，请检查网络",
                  icon: "none",
                });
              });
          },
          fail: (err) => {
            console.error("读取图片文件失败", err);
            Taro.showToast({
              title: "读取图片文件失败",
              icon: "none",
            });
          },
        });
      },
      fail: (err) => {
        console.error("选择图片失败", err);
        Taro.showToast({
          title: "选择图片失败",
          icon: "none",
        });
      },
    });
  };

  const uploadFile = (filePath, type) => {
    AuthUtil.uploadFile(filePath).then((res: any) => {
      if (res) {
        const imagePath = res.url;
        const imageId = res.id;
        console.log(type, imagePath);
        if (type == "drivingFront") {
          setDrivingLicenseFront(imagePath);
          setDrivingLicenseFrontId(imageId);
        } else if (type == "drivingBack") {
          setDrivingLicenseBack(imagePath);
          setDrivingLicenseBackId(imageId);
        } else if (type == "idFront") {
          setIdCardFront(imagePath);
          setIdCardFrontId(imageId);
        } else if (type == "idBack") {
          setIdCardBack(imagePath);
          setIdCardBackId(imageId);
        }
      }
    });
  };
  const customTheme = {
    nutuiStepsBaseLineWidth: "70%",
    nutuiStepsProcessIconBgColor: "#3768FA",
    nutuiStepsProcessIconColor: "#fff",
    nutuiStepsProcessTitleColor: "#3768FA",
    nutuiStepsProcessTitleFontSize: "15px",
    nutuiStepsProcessTitleFontWeight: "500",
    nutuiStepsFinishIconColor: "#3768FA",
    nutuiStepsFinishTitleColor: "#3768FA",
    nutuiStepsFinishLineBackground: "#3768FA",
  };
  const handleClearIdcar = (type) => {
    if (type === "idFront") {
      setIdCardFront(null);
      form.setFieldsValue({
        realName: "",
        identityNumber: "",
        contactAddress: "",
      }); // 重置相关的输入字段
    } else if (type === "idBack") {
      setIdCardBack(null);
    }
  };

  const handleClear = (type) => {
    if (type === "drivingFront") {
      setDrivingLicenseFront(null);
      form.setFieldsValue({
        plateNumber: "",
        vehicleIdentificationNumber: "",
        engineNumber: "",
        brandModel: "",
        vehicleType: "",
        name: "",
      }); // 重置相关的输入字段
    } else if (type === "drivingBack") {
      setDrivingLicenseBack(null);
    }
  };
  const handleImage = (value) => {
    setImages([{ src: value }]);
    setShowPreview(true);
  };
  return (
    <View className="driving-license">
      <ImagePreview
        autoPlay
        closeIcon
        images={images}
        visible={showPreview}
        onClose={() => setShowPreview(false)}
      />
      <ConfigProvider theme={customTheme}>
        <Steps value={1}>
          <Step value={1} title="步骤一" />
          <Step value={2} title="步骤二" />
        </Steps>
      </ConfigProvider>
      <Row>
        <Col className="font-bold">行驶证</Col>
      </Row>
      <div className="driving">
        <div className="driving_img">
          {!drivingLicenseFront ? (
            <div className="driving_name">点击上传行驶证主页</div>
          ) : (
            ""
          )}
          {drivingLicenseFront ? (
            <>
              <div
                className="clear_btn"
                onClick={() => handleClear("drivingFront")}
              >
                <Close />
              </div>
              <Image
                className="car_info"
                src={drivingLicenseFront}
                onClick={() => {
                  handleImage(drivingLicenseFront);
                }}
              />
            </>
          ) : (
            <Image
              className="car_info"
              src={Drivingup}
              onClick={() =>
                handleImageSelect(setDrivingLicenseFront, "drivingFront")
              }
            />
          )}
        </div>
        <div className="driving_img">
          {!drivingLicenseBack ? (
            <div className="driving_name">点击上传行驶证副页</div>
          ) : (
            ""
          )}
          {drivingLicenseBack ? (
            <>
              <div
                className="clear_btn"
                onClick={() => handleClear("drivingBack")}
              >
                <Close />
              </div>
              <Image
                className="car_info"
                src={drivingLicenseBack}
                onClick={() => {
                  handleImage(drivingLicenseBack);
                }}
              />
            </>
          ) : (
            <Image
              className="car_info"
              src={Driving}
              onClick={() =>
                handleImageSelect(setDrivingLicenseBack, "drivingBack")
              }
            />
          )}
        </div>
      </div>
      <Row>
        <View
          className="driving_bottom"
          style={{ whiteSpace: "nowrap", fontSize: "26rpx" }}
        >
          <View>请确保证件</View>
          <View style={{ color: "#1c8cdf" }}>
            边框完整无遮挡、内容清晰无反光
          </View>
        </View>
      </Row>

      <Row>
        <Form
          form={form}
          divider
          labelPosition="left"
          onFinish={(values) => submitSucceed(values)}
          onFinishFailed={(values, errors) => submitFailed(errors)}
          footer={
            <div
              style={{
                display: "flex",
                justifyContent: "center",
                width: "100%",
              }}
            >
              <Button className="form_buttom" nativeType="reset">
                重置
              </Button>
              <Button
                className="form_buttom"
                nativeType="submit"
                type="primary"
                style={{ marginLeft: "20px", background: "#009afa" }}
              >
                提交
              </Button>
            </div>
          }
        >
          <FormItem
            label="车辆牌号"
            name="plateNumber"
            rules={[{ required: true, message: "请输入车辆牌号" }]}
          >
            <Input placeholder="请输入车辆牌号" type="text" />
          </FormItem>
          <FormItem
            label="车辆识别代码"
            name="vehicleIdentificationNumber"
            rules={[{ required: true, message: "请输入车辆识别代码" }]}
          >
            <Input placeholder="请输入车辆识别代码" type="text" />
          </FormItem>
          <FormItem
            label="发动机号码"
            name="engineNumber"
            rules={[{ required: true, message: "请输入发动机号码" }]}
          >
            <Input placeholder="请输入发动机号码" type="text" />
          </FormItem>
          <FormItem
            label="品牌型号"
            name="brandModel"
            rules={[{ required: true, message: "请输入品牌型号" }]}
          >
            <Input placeholder="请输入品牌型号" type="text" />
          </FormItem>
          <FormItem
            label="车辆类型"
            name="vehicleType"
            rules={[{ required: true, message: "请输入车辆类型" }]}
          >
            <Input placeholder="请输入车辆类型" type="text" />
          </FormItem>
          <FormItem
            label="车辆所有人"
            name="name"
            rules={[{ required: true, message: "请输入车辆所有人" }]}
          >
            <Input placeholder="请输入车辆所有人" type="text" />
          </FormItem>
          <FormItem
            label="核载人数"
            name="ratedCapacity"
            rules={[{ required: true, message: "请输入核载人数" }]}
          >
            <Input placeholder="请输入核载人数" type="number" />
          </FormItem>
          <Row>
            <Col className="font-bold">身份证</Col>
          </Row>
          <div className="driving">
            <div className="driving_img">
              {!idCardFront ? (
                <div className="driving_name">身份证人像面</div>
              ) : (
                ""
              )}
              {idCardFront ? (
                <>
                  <div
                    className="clear_btn"
                    onClick={() => handleClearIdcar("idFront")}
                  >
                    <Close />
                  </div>
                  <Image
                    className="car_info"
                    src={idCardFront}
                    onClick={() => {
                      handleImage(idCardFront);
                    }}
                  />
                </>
              ) : (
                <Image
                  className="car_info"
                  src={CardFront}
                  onClick={() => handleImageSelect(setIdCardFront, "idFront")}
                />
              )}
            </div>
            <div className="driving_img">
              {!idCardBack ? (
                <div className="driving_name">身份证国徽面</div>
              ) : (
                ""
              )}

              {idCardBack ? (
                <>
                  <div
                    className="clear_btn"
                    onClick={() => handleClearIdcar("idBack")}
                  >
                    <Close />
                  </div>
                  <Image
                    className="car_info"
                    src={idCardBack}
                    onClick={() => {
                      handleImage(idCardBack);
                    }}
                  />
                </>
              ) : (
                <Image
                  className="car_info"
                  src={CardBack}
                  onClick={() => handleImageSelect(setIdCardBack, "idBack")}
                />
              )}
            </div>
          </div>
          <FormItem
            label="真实姓名"
            name="realName"
            rules={[{ required: true, message: "请输入真实姓名" }]}
          >
            <Input placeholder="请输入真实姓名" type="text" />
          </FormItem>
          <FormItem
            label="身份证号"
            name="identityNumber"
            rules={[{ required: true, message: "请输入身份证号" }]}
          >
            <Input placeholder="请输入身份证号" type="text" />
          </FormItem>
          <FormItem
            label="联系地址"
            name="contactAddress"
            style={{ height: "52px" }}
            rules={[{ required: true, message: "请输入联系地址" }]}
          >
            <TextArea style={{ height: "52px" }} placeholder="请输入联系地址" />
          </FormItem>
          <FormItem
            label="身份证有效期"
            name="idCardDate"
            rules={[{ required: true, message: "请输入身份证有效期" }]}
          >
            <Input placeholder="请输入身份证有效期" type="text" />
          </FormItem>
        </Form>
      </Row>
    </View>
  );
}

function CarInfo() {
  return (
    <View className="car-info">
      <DrivingLicense />
    </View>
  );
}

export default CarInfo;
